package controllers

import (
	"go/dao"
	"go/models"
	"go/pkg/app"
	"go/pkg/e"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

func AddSC(c *gin.Context) {
	m := make(map[string]string, 1024)
	c.ShouldBind(&m)
	cno := m["cno"]
	sno := m["sno"]
	grade := m["grade"]

	sc := models.Sc{
		Cno:   cno,
		Sno:   sno,
		Grade: grade,
		IsDel: false,
	}

	err := dao.AddSC(sc)

	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, sc, "添加成功")
}

func DelSC(c *gin.Context) {
	json := make(map[string]string, 1024)
	c.ShouldBind(&json)

	cno := json["cno"]
	sno := json["sno"]
	grade := json["grade"]

	sc := models.Sc{
		Cno:   cno,
		Sno:   sno,
		Grade: grade,
		IsDel: true,
	}

	db := dao.GetDB()
	err := db.Table("sc").Where("sno = ?", sno).Update("is_del", true).Error
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, sc, "删除成功")
}

func UpdateSC(c *gin.Context) {
	m := make(map[string]string, 1024)
	c.ShouldBind(&m)

	cno := m["cno"]
	sno := m["sno"]
	grade := m["grade"]

	sc := models.Sc{
		Cno:   cno,
		Sno:   sno,
		Grade: grade,
		IsDel: false,
	}

	err := dao.UpdateSC(sc)

	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, sc, "更新成功")
}

func GetSC(c *gin.Context) {
	page := -1
	if arg := c.Query("page"); arg != "" {
		page = com.StrTo(arg).MustInt()
	}
	limit := -1
	if arg := c.Query("limit"); arg != "" {
		limit = com.StrTo(arg).MustInt()
	}
	searchName := ""
	if arg := c.Query("searchName"); arg != "" {
		searchName = arg
	}
	scParam := map[string]interface{}{
		"page":       page,
		"limit":      limit,
		"searchName": searchName,
	}
	info, total, err := dao.GetSC(scParam)
	//fmt.Println(info);
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total}, "OK")
}
